<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>档案检索申请</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <jsp:include page="/inc/head.jsp" flush="true" />
    <link href="${basePath}/js/activiti/qtip/jquery.qtip.min.css" type="text/css" rel="stylesheet" />
    <link href="${basePath}/js/activiti/jquery-ui-1.9.2.custom.css" type="text/css" rel="stylesheet" />
    <link href="${basePath}/js/activiti/style-ui.css" type="text/css" rel="stylesheet" />
    <jsp:include page="/inc/footer.jsp" flush="true" />
    <!-- picker -->
    <script src="${basePath}/js/My97DatePicker/WdatePicker.js"></script>
    <script src="${basePath}/js/activiti/qtip/jquery.qtip.pack.js" type="text/javascript"></script>
    <script src="${basePath}/js/activiti/jquery.outerhtml.js" type="text/javascript"></script>
    <script src="${basePath}/js/activiti/jquery-ui-1.9.2.min.js" type="text/javascript"></script>
    <script src="${basePath }/js/module/activiti/workflow.js"></script>
    <script src="${basePath }/js/tip.js"></script>
    <style>
        .searchApply .bootstrap-table .fixed-table-toolbar .bs-bars {
            margin-top: 0;
        }
        #searchApplyForm  .content {
            padding-right: 0;
        }
        #searchApplyForm  td input,#searchApplyForm  td select {
            height:28px;
            border:1px solid #aaa;
            border-radius:3px;
            padding-left: 5px;
        }
        #searchApplyForm  td #planReturnTime {
            width: 155px;
        }
        #searchApplyForm  td #auditDept {
            padding-left: 0;
        }
        #searchApplyForm  td textarea {
            border:1px solid #aaa;
            border-radius:3px;
            padding-left: 5px;
            resize:none;
        }
        .select2-container .select2-selection--single{
            padding-left: 5px;
            padding-right: 8px;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            padding: 0 12px 0 0;
            margin-top: -5px;
        }
    </style>
</head>

<body class="hold-transition skin-blue sidebar-mini searchApply" style="overflow:hidden;">
    <!-- Main content -->
    <section class="content">
        <!-- /rowToolBar -->
        <div id="rowToolBar" class="row" style="height: 100%;">
            <div class="col-xs-12">
                <div class="box box-info" style="margin:0;border-top:0;box-shadow:none;">
                    <form class="form-horizontal">
                        <!-- /.box-header -->
                        <div class="box-body btn-group" style="padding:0;">
                            <shiro:hasPermission name="cms:search:apply">
                                <button id="btn_add" type="button" class="btn btn-default"
                                    onclick="searchApplyAction()">
                                    <span class="glyphicon glyphicon-paste" aria-hidden="true"></span>检索申请
                                </button>
                            </shiro:hasPermission>
                            <shiro:hasPermission name="cms:search:mySearch">
                                <button id="btn_mySearch" type="button" class="btn btn-default"
                                        onclick="mySearchAction()">
                                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>我的检索
                                </button>
                            </shiro:hasPermission>
                            <shiro:hasPermission name="cms:borAudit:myHistory">
                                <button id="btn_history" type="button" class="btn btn-default"
                                    onclick="checkHistoryApplyAction()">
                                    <span class="glyphicon glyphicon-paste" aria-hidden="true"></span>我的历史审批
                                </button>
                            </shiro:hasPermission>
                        </div>
                        <!-- /.box-body -->
                    </form>
                    <!-- /.form -->
                </div>
                <!-- /.box -->
            </div>
            <!-- /.col-xs-12 -->
        </div>
        <div id="myRunDiv">
            <!-- 当前我的运行的table -->
            <table id="myRunTable">
            </table>
        </div>

        <div id="myHistoryDiv" style="display: none">
            <!-- 当前的历史table -->
            <table id="myHistoryTable">
            </table>
        </div>

        <div id="mySearchDiv">
            <!-- 当前我的检索的table -->
            <table id="mySearchTable">
            </table>
        </div>

        <%--检索申请填写资料模态框--%>
        <div id="searchApplyModal" class="modal fade bs-example-modal-lg addUpdateInfo" role="dialog"
            aria-labelledby="myLargeModalLabel">
            <div class="modal-dialog " role="document">
                <div class="modal-content" style="width: 600px;">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">填写检索申请单</h4>
                    </div>
                    <form id="searchApplyForm" class="modal-body form-horizontal form-bordered form-row-strippe"
                        data-toggle="validator" enctype="multipart/form-data">
                        <table style="width: 100%">
                            <tr>
                                <td class="content ">
                                    申请检索部门
                                </td>
                                <td class="form-group" id="auditDeptTd">
                                    <select id="auditDept" name="auditDept"
                                        style="width: 155px;height: 26px;display: none">
                                    </select>
                                    <input type='text' id="auditDeptInput" name="auditDept" value=''
                                        style="display: none" />
                                </td>
                                <td class="content">
                                    检索截止时间
                                </td>
                                <td class="form-group">
                                    <input type='planReturnTime' id="planReturnTime" name="" onClick='WdatePicker()' />
                                </td>
                            </tr>
                            <tr id="identityProveTr" style="display: none">
                                <td class="content">
                                    检&nbsp;&nbsp;索&nbsp;&nbsp;证&nbsp;&nbsp;明
                                </td>
                                <td class="form-group" id="identityProve">
                                    <input type='file' id="identityProveFile" name="file" style="width: 98%" />
                                </td>
                            </tr>
                            <tr>
                                <td class="content">
                                    检&nbsp;&nbsp;索&nbsp;&nbsp;内&nbsp;&nbsp;容
                                </td>
                                <td colspan="5" class="form-group">
                                    <textarea rows="1" cols="3" id="auditDetail" name="auditDetail"
                                        style="width: 98%"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td class="content">
                                    检&nbsp;&nbsp;索&nbsp;&nbsp;原&nbsp;&nbsp;因
                                </td>
                                <td colspan="5" class="form-group">
                                    <input type='text' class="auditReason" id="auditReason" name="auditReason" value=''
                                        style="width: 98%" />
                                </td>
                            </tr>
                            <tr id="sendPointUserDiv" style="display: none">
                                <td class="content">
                                    指定下级领导审批
                                </td>
                                <td colspan="5" class="form-group">
                                    <select id="userTable" data-delegateUser="" style="width: 98%">
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </form>

                    <div class="modal-footer">
                        <button type="button" class="btn green" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="createDefine"
                            onclick="auditSubmitButton(this)">提交申请</button>
                    </div>
                </div>
            </div>
        </div>
    </section>

</body>
<script>
    var selectionIds = {};  //保存选中ids,以及该id对应的状态
    //我的正在运行的流程
    var $myRunTable = $("#myRunTable");
    //我的历史申请流程
    var $myHistoryTable = $("#myHistoryTable");
    //我的检索申请结果
    var $mySearchTable = $("#mySearchTable");
    $(function () {
        myRunAction();
        loadOrgMessage();
    })

    /**
     * 表格高度自适应
     * @return
     * winTop 浏览器视口高度
     * header 顶部通栏
     * breadcrumb 面包屑
     * mainFooter 底部
     */
    function setHeight(){
        var winTop = $(window.top).height(),
            header = window.top.document.querySelector('.main-header').offsetHeight,
            breadcrumb =  window.top.document.querySelector('.breadcrumb').offsetHeight,
            mainFooter = window.top.document.querySelector('.main-footer').offsetHeight;
        return winTop-header-breadcrumb-mainFooter-50;
    }

    function loadOrgMessage() {
        $.ajax({
            url: "${basePath}/pcwindow/getOrganization",
            type: "post",
            success: function (data) {
                if (data == "0") {
                    //无组织机构进行借阅
                    //清空部门数据
                    $("#auditDept").empty();
                    $("#auditDeptTd").find("#auditDept").hide();
                    $("#auditDeptTd").find("#auditDeptInput").show();
                    $("#identityProveTr").show();
                } else {
                    //无组织机构进行借阅
                    //清空部门数据
                    $("#auditDept").empty();
                    $("#auditDeptTd").find("#auditDept").show();
                    $("#auditDeptTd").find("#auditDeptInput").hide();
                    $("#identityProveTr").hide();
                    var option = $("#auditDept");
                    option.empty();
                    $.each(data, function (i, items) {
                        option.append("<option value=" + items.organizationId + ">" + items.name + "</option>")
                    })
                }
            }
        })
    }
    //显示历史流程
    function checkHistoryApplyAction() {
        $("#myRunDiv").hide();
        $("#myHistoryDiv").show();
        $("#mySearchDiv").hide();
        $myHistoryTable.bootstrapTable("destroy");
        showMyHistoryTable();
    }

    /************************************我的历史流程总览（开始）****************************/
    function showMyHistoryTable() {
        $myHistoryTable.bootstrapTable({
            url: "${basePath}/pcwindow/findFinishedProcessInstaces",
            queryParams: { activitiType: "searchActiviti" },//此参数识别当前查询的正在运行的流程为何种流程2：检索流程
            striped: true,
            search: false,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: false,
            detailFormatter: 'detailFormatter',
            pagination: true,
            pageSize: 50,
            pageList:[50,100],
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                { field: 'id', visible: false },//借阅登记表的id
                { field: 'taskId', visible: false },//当前工作流的流程id
                { field: 'registerNum', title: '登记号', sortable: true, align: 'center' },
                //                {field: 'taskType', title: '申请类型', align: 'center',formatter:'taskTypeFormat'},
                { field: 'borUserName', title: '申请人', align: 'center' },
                { field: 'extend1', title: '检索内容', align: 'center' },
                //                {field: 'createTime', title: '申请时间', align: 'center',formatter:'timeFormat'},
                { field: 'planReturnTime', title: '检索截止时间', align: 'center', formatter: 'planReturnFormat' },
                { field: 'taskCreateTime', title: '审批申请时间', align: 'center', formatter: 'timeFormat' },
                { field: 'taskFinishTime', title: '审批结束时间', align: 'center', formatter: 'timeFormat' },
                //                {field: 'borPurpose', title: '流程结束原因', align: 'center',formatter:'borPurposeFormat'},
                //                {field: 'version', title: '流程版本', align: 'center',formatter:'versionFormat'},
                { field: 'extend2', title: '审批结果', align: 'center', formatter: 'extend2Format' },
            ],
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        })
        $myHistoryTable.bootstrapTable('resetView',{height:setHeight()});
    }

    //审批结果初始化
    function extend2Format(value, row, index) {
        if (value == 0) {
            return '<span class="label label-default">不通过</span>';
        } else {
            return '<span class="label label-success">通过</span>';
        }
    }

    //初始化流程结束原因
    function borPurposeFormat(value, row, index) {
        if (value == null) {
            return "正常结束";
        } else {
            return value;
        }
    }

    //流程状态初始化
    function versionFormat(value, row, index) {
        return " V : " + row.actVersion;
    }

    /************************************我的历史流程总览（结束）****************************/
    /************************************我的运行中的流程总览（开始）****************************/
    //查看运行中的流程
    function myRunAction() {
        $("#myHistoryDiv").hide();
        $("#myRunDiv").show();
        $("#mySearchDiv").hide();
        $myRunTable.bootstrapTable("destroy");
        showMyRun();
    }

    //执行我运行中的流程数据
    function showMyRun() {
        $myRunTable.bootstrapTable({
            url: "${basePath}/pcwindow/findRunningProcessInstaces",
            queryParams: { activitiType: "searchActiviti" },//此参数识别当前查询的正在运行的流程为何种流程2：检索流程
            striped: true,
            search: false,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: false,
            detailFormatter: 'detailFormatter',
            pagination: true,
            pageList: [10, 25, 50],
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                { field: 'id', visible: false },//借阅登记表的id
                { field: 'taskId', visible: false },//当前工作流的流程id
                { field: 'registerNum', title: '登记号', sortable: true, align: 'center' },
                //                {field: 'taskType', title: '申请类型', align: 'center',formatter:'taskTypeFormat'},
                { field: 'extend1', title: '检索内容', align: 'center' },
                { field: 'createTime', title: '申请时间', align: 'center', formatter: 'timeFormat' },
                { field: 'planReturnTime', title: '检索截止时间', align: 'center', formatter: 'planReturnFormat' },
                //                {field: 'taskName', title: '当前节点', align: 'center',formatter:'taskNameFormat'},
                //                {field: 'status', title: '流程状态', align: 'center',formatter:'statusFormat'},
                { field: 'taskAssignee', title: '当前处理人', align: 'center' }
            ],
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        })
        $myRunTable.bootstrapTable('resetView',{height:setHeight()});
    }
    //初始化时间操作
    function timeFormat(value, row, index) {
        if (typeof (value) == "number") {
            return formatDateTime(value);
        } else {
            var time = value.time;
            return formatDateTime(time);
        }
    }

    //初始化检索操作
    function taskTypeFormat(value, row, index) {
        if (value == "3") {
            return "检索";
        }
    }

    //初始化检索到期时间操作
    function planReturnFormat(value, row, index) {
        if (typeof (value) == "number") {
            return formatshortDateTime(value);
        } else {
            var time = value.time;
            return formatshortDateTime(time);
        }
    }

    //流程状态初始化
    function taskNameFormat(value, row, index) {
        return '<a style="color: blue" href="#" pid="' + row.processId + '" pdid="' + row.processDefinitionId + '" onclick="watchProcessPic(this);" title="点击查看流程图">' + value + '</a>';
    }

    /**
     * 查看流程图
     */
    function watchProcessPic(evn) {
        var processId = $(evn).attr("pid");
        var processDefinitionId = $(evn).attr("pdid");
        graphTrace(processId, processDefinitionId);
    }

    //流程状态初始化
    function statusFormat(value, row, index) {
        return row.suspended ? "已挂起" : "正常" + " V : " + row.actVersion;
    }

    /**
     *	操作按钮
     */
    function actionFormatter(value, row, index) {
        return '<a href="javascript:void(0)" style="color:#01579b;" onclick="borrowAction(' + row.itemId + ',1)" >借阅</a>';
    }

    /************************************我的运行中的流程总览（结束）****************************/

    /************************************我的检索申请（开始）************************************/

    //显示我的检索申请action
    function mySearchAction() {
        $("#myRunDiv").hide();
        $("#mySearchDiv").show();
        $("#myHistoryDiv").hide();
        $mySearchTable.bootstrapTable("destroy");
        showMySearchTable();
    }

    //执行我的检索的数据表格
    function showMySearchTable(){
        $mySearchTable.bootstrapTable({
            url: "${basePath}/pcwindow/mySearchData",
//            queryParams: '',//此参数识别当前查询的正在运行的流程为何种流程2：检索流程
            striped: true,
            search: false,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: false,
            detailFormatter: 'detailFormatter',
            pagination: true,
            pageList: [10, 25, 50],
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                { field: 'id', visible: false },//借阅登记表的id
                { field: 'registerNum', title: '登记号', sortable: true, align: 'center' },
                { field: 'extend1', title: '检索内容', align: 'center' },
                { field: 'createTime', title: '申请时间', align: 'center', formatter: 'timeFormat' },
                { field: 'planReturnTime', title: '检索截止时间', align: 'center', formatter: 'planReturnFormat' },
                { field: 'borStatus', title: '当前状态', align: 'center', formatter: 'borStatusFormat' }
            ],
            onLoadSuccess:function(data){

                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        })
        $mySearchTable.bootstrapTable('resetView',{height:setHeight()});
    }

    //检索状态初始化
    function borStatusFormat(value, row, index) {
        if(value==0){
            return '<span class="label label-default">已通过，未授权</span>';
        }else{
            return '<span class="label label-success">已通过，已授权</span>';
        }
    }
    /************************************我的检索申请（开始）**********************************/

    /* 检索 申请 弹出框 */
    function searchApplyAction() {
        $("#searchApplyForm")[0].reset()//打开前先清空表单
        //获取检索申请的流程第一个审批人是否为自定义 若为自定义 则选择已有人员进行设置
        $.ajax({
            url: "${basePath}/activiti/common/selectFirstTaskUser/searchAct/''",
            data: "",
            type: "get",
            async: false,
            dataType: "json",
            success: function (data) {
                var code = data.code;
                //当前为指定人选
                if (code == 1) {
                    $("#sendPointUserDiv").show();
                    // 当前流程中 赋予的代表用户${user }===> user
                    var pointUser = data.message;
                    $("#userTable").attr("data-delegateUser", pointUser);
                    $.ajax({
                        url: "${basePath}/pcwindow/showAllUser",
                        type: 'get',
                        data: "",
                        dataType: "json",
                        success: function (data) {
                            $('#userTable').empty();
                            $('#userTable').select2({
                                placeholder: '请选择下一个审批人',
                                allowClear: true
                            });
                            var allList = data.rows;
                            var option = '';
                            for (var index in allList) {
                                var user = allList[index];
                                option += "<option value='" + user.firstName + "'>" + user.lastName + "</option>";
                            }
                            var $option = $(option);
                            $("#userTable").append($option);
                        }
                    })
                } else {
                    if (data.message != null) {
                        confirmEvent(data.message);
                    }
                    $("#sendPointUserDiv").hide();
                    $("#userTable").attr("data-delegateUser", "");
                }
            }
        })
        $('#searchApplyModal').modal('show');
    }

    /*检索申请提交*/
    function auditSubmitButton(evn) {
        $(evn).attr("disabled", true);
        var auditDept;
        var planReturnTime;
        var auditDetail;
        var auditReason;
        var formData = new FormData();
        var delegateUser;

        planReturnTime = $("#planReturnTime").val();
        auditDetail = $("#auditDetail").val();
        auditReason = $("#auditReason").val();
        //替代实际人
        delegateUser = $("#userTable").attr("data-delegateUser");
        formData.append("auditDetail", auditDetail);
        formData.append("auditReason", auditReason);
        formData.append("planReturnTime", planReturnTime);
        formData.append("delegateUser", delegateUser);
        //判断当前用户有无组织机构列表
        var auditDeptLength = $("#auditDept").find("option").length;
        //如果用户组织机构长度大于0 则该用户为有组织机构用户
        if (auditDeptLength > 0) {
            auditDept = $("#auditDept").val();
            if (auditDept == "" || planReturnTime == "" || auditReason == "" || auditDetail == "") {
                confirmEvent("信息不完整，请完整信息后提交！");
                $(evn).attr("disabled", false);
                return;
            }
            formData.append("auditDept", auditDept);
        } else {
            auditDept = $("#auditDeptInput").val();
            formData.append("auditDept", auditDept);
            var identityProveFile = $("#identityProveFile")[0].files[0];
            formData.append("file", identityProveFile);
            if (identityProveFile == null || auditDept == "" || planReturnTime == "" || auditReason == "" || auditDetail == "") {
                confirmEvent('信息不完整，请完整信息后提交！');
                $(evn).attr("disabled", false);
                return;
            }
        }
        //判断当前是否为指定审批人表达式
        if (delegateUser != "") {
            var userName = $("#userTable").val();
            if(userName==null){
                confirmEvent('请指定下一个审批人！');
                $(evn).attr("disabled",false);
                return;
            }
            formData.append("userName", userName);
        }
        var returnData = strToDate(planReturnTime);
        var nowDate = new Date();
        if (nowDate > returnData) {
            confirmEvent('时间不可小于或等于当前时间');
            $(evn).attr("disabled", false);
            return;
        }
        $.ajax({
            url: "${basePath}/pcwindow/sendSearchAct",
            method: "post",
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == 0) {
                    confirmEvent("发起检索申请失败！");
                    $(evn).attr("disabled", false);
                } else {
                    $("#searchApplyModal").modal("hide");
                    $(evn).attr("disabled", false);
                    confirmEvent("发起检索申请成功！");
                    $myRunTable.bootstrapTable('refresh');
                }
            }
        })
    }


    /********************** bootStrap Table分页多选的解决方案问题 *********************/

    //选中事件操作数组
    var union = function (json, jsonIds) {
        $.each(jsonIds, function (key, value) {
            if (!json.hasOwnProperty(key)) {
                json[key] = value;
            }
        });
        return json;
    };
    //取消选中事件操作数组
    var difference = function (json, jsonIds) {
        $.each(jsonIds, function (key, value) {
            if (json.hasOwnProperty(key)) {
                delete json[key];
            }
        });
        return json;
    };
    var _ = { "union": union, "difference": difference };
    //绑定选中事件、取消事件、全部选中、全部取消
    $("#child_table").on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table', function (e, rows) {
        var jsonIds = {};
        rows = !$.isArray(rows) ? [rows] : rows
        $.each(rows, function (index, row) {
            jsonIds[row.itemId] = row.itemStatus;
        });
        func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
        selectionIds = _[func](selectionIds, jsonIds);
    });

    function responseHandler(res) {
        $.each(res.rows, function (i, row) {
            //判断当前行的数据id是否存在与选中的json key 相同的，存在则将多选框状态变为true
            row.ck = selectionIds.hasOwnProperty(row.itemId) == 1;
        });
        return res;
    }
    /********************** bootStrap Table分页多选的解决方案问题 ********************/
</script>

</html>